﻿using HtmlAgilityPack;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using Utils;
using Wrapper;
using System.Net;

namespace Logic
{
    /// <summary>
    /// 店员积分 网站登录，推荐逻辑处理类
    /// </summary>
    public class DYJFLogic
    {
        private string LOGIN_SHOW_URL = "http://www.ha.10086.cn/tiyan/channel/tologon.action";

        private string LOGIN_CHECKIMG_URL = "https://ha.ac.10086.cn/checkImage";

        private string LOGIN_URL = "https://ha.ac.10086.cn/login";

        //http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action?loginPhoneNo=13526851141&errorCode=4001&authTimes=2
        private string LOGIN_FAIL_URL = "http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action";

        private string LOGIN_SUC_URL = "http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel";

        private string SSOPOST_URL = "https://ha.ac.10086.cn/SSOPOST";

        private string IMPLICITLOGIN_URL = "http://www.ha.10086.cn/tiyan/SSOClient/implicitLogin.action";

        private string VALIDATESSO_URL = "http://www.ha.10086.cn/tiyan/channel/validateSSO.action";

        private string INDEX_URL = "http://www.ha.10086.cn/tiyan/channel/index.action";

        /// <summary>
        /// 酬金查询
        /// </summary>
        private string BRBD_URL = "http://www.ha.10086.cn/tiyan/channel/brbd.action";

        /// <summary>
        /// 推荐查询
        /// </summary>
        private string QEBDatas_URL = "http://www.ha.10086.cn/tiyan/channel/qEBDatas.action";



        //打开登录页面返回的cookie
        string cookieCode = "";
        string tiyanJSESSIONID = "";
        //打开登录页面返回的cookie

        //统一认证 session
        string haJSESSIONID = "";
        //统一认证 session

        //tiyan登录
        string CmProvid = "";
        string cmtokenid = "";
        string cmtokenidHeNan = "";
        string CmWebtokenid = "";
        string passtype = "";
        //tiyan登录

        string TiyanWebtokenid = "";

        //10086统一认证所需cookie
        CookieCollection haRespCookieList = new CookieCollection();

        //店员积分网站认证所需cookie
        CookieCollection tiyanCookieList = new CookieCollection();

        HttpUtils httpUtils = null;
        private string sid;
        private string referer = "";
        crifanLib lib = new crifanLib();

        private string imgPath = "dyjfimg\\";

        public DYJFLogic(string _sid)
        {
            sid = _sid;
            httpUtils = new HttpUtils(_sid);

            if (!Directory.Exists(imgPath))
            {
                Directory.CreateDirectory(imgPath);
            }
            imgPath = imgPath + DateTime.Now.ToString("yyyyMMdd") + "\\";
            if (!Directory.Exists(imgPath))
            {
                Directory.CreateDirectory(imgPath);
            }
        }

        public string Get_Login_Show()
        {
            /*
             <input type="hidden" name="IDToken2" value="2">
			<input type="hidden" name="authType" value="userPass">
			<input type="hidden" name="SysSeqNO" value="5000">
			<input type="hidden" name="goto" value='http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel'/>
			<input type="hidden" name="BackURL" value='http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action'/>
			<input type="hidden" name="SPID" value='http://www.ha.10086.cn/tiyan'/>
             */
            string respCookie = "";
            string result = httpUtils.DoGet(LOGIN_SHOW_URL, "", null, out respCookie);

            CookieCollection respCookieList = lib.parseSetCookie(respCookie, ".10086.cn");
            for (int i = 0; i < respCookieList.Count; i++)
            {
                Cookie temp = respCookieList[i];
                if (temp.Name == "cookieCode")
                {
                    cookieCode = temp.Value;
                }
                else if(temp.Name=="JSESSIONID")
                {
                    tiyanJSESSIONID = temp.Value;
                }
            }

            return respCookie;
        }

        public bool DownImage()
        {
            referer = LOGIN_SHOW_URL;
            string respCookie = "";
            bool suc = httpUtils.Download(LOGIN_CHECKIMG_URL, imgPath, sid + ".jpg", referer, null, out respCookie);
            CookieCollection respCookieList = lib.parseSetCookie(respCookie, ".10086.cn");
            for (int i = 0; i < respCookieList.Count; i++)
            {
                Cookie temp = respCookieList[i];
                if (temp.Name == "JSESSIONID")
                {
                    haJSESSIONID = temp.Value;
                }
            }
            return suc;
        }

        /// <summary>
        /// 识别验证码
        /// </summary>
        /// <returns></returns>
        public CodeInfo RecognizeRadon()
        {
            string fullPath = imgPath + sid + ".jpg";
            return WrapperUtil.getInstance().recognize(fullPath);
        }

        //成功则跳转ssopost页面，失败跳转dianyuanFai.action
        public bool Login(string phone, string pwd, string radom)
        {
            bool suc = false;
            StringBuilder sb = new StringBuilder("IDToken1=" + phone);
            sb.Append("&IDToken3=" + pwd);
            sb.Append("&IDToken4=" + radom);
            sb.Append("&IDToken2=2");
            sb.Append("&authType=userPass");
            sb.Append("&SysSeqNO=5000");

            sb.Append("&goto=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel", Encoding.UTF8));
            sb.Append("&BackURL=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan/SSOClient/dianyuanFail.action", Encoding.UTF8));
            sb.Append("&SPID=" + HttpUtility.UrlEncode("http://www.ha.10086.cn/tiyan", Encoding.UTF8));

            CookieCollection reqCookieList = new CookieCollection();
            reqCookieList.Add(new Cookie("JSESSIONID", haJSESSIONID, "/", ".10086.cn"));
            string respCookie = "";
            string loginRespHtml = httpUtils.DoPost(LOGIN_URL, sb.ToString(), referer, reqCookieList, out respCookie);
            haRespCookieList = lib.parseSetCookie(respCookie, ".10086.cn");
            for (int i = 0; i < haRespCookieList.Count; i++)
            {
                Cookie temp = haRespCookieList[i];
                if (temp.Name == "cmtokenid")
                {
                    cmtokenid = temp.Value;
                }
                else if (temp.Name == "passtype")
                {
                    passtype = temp.Value;
                }
                else if (temp.Name == "CmWebtokenid")
                {
                    CmWebtokenid = temp.Value + ",ha";
                    temp.Value = CmWebtokenid;
                }
                else if (temp.Name == "CmProvid")
                {
                    CmProvid = temp.Value;
                }
                else if (temp.Name == "cmtokenidHeNan")
                {
                    cmtokenidHeNan = temp.Value;
                }
            }

            
            tiyanCookieList.Add(haRespCookieList);

            Cookie temp1 = new Cookie();
            temp1.Name = "cookieCode";
            temp1.Value = cookieCode;
            temp1.Domain = ".10086";
            tiyanCookieList.Add(temp1);

            Cookie temp2 = new Cookie();
            temp2.Name = "JSESSIONID";
            temp2.Value = tiyanJSESSIONID;
            temp2.Domain = ".10086";
            tiyanCookieList.Add(temp2);


            string foundRespHtml = httpUtils.DoGet(loginRespHtml, referer, tiyanCookieList, out respCookie);

            string SAMLRequest = "";
            string RelayState = "";

            //解析 登录的返回数据
            AnalizeLoginData(foundRespHtml, out SAMLRequest, out RelayState);
            if (SAMLRequest == "" || RelayState == "")
            {
                Log.PrintLog("第一层验证错误：" + loginRespHtml);
            }
            else
            {
                sb = new StringBuilder("SAMLRequest=" + HttpUtility.UrlEncode(SAMLRequest));
                sb.Append("&RelayState=" + HttpUtility.UrlEncode(RelayState));

                Cookie temp3 = new Cookie();
                temp3.Name = "JSESSIONID";
                temp3.Value = haJSESSIONID;
                temp3.Domain = ".10086";
                haRespCookieList.Add(temp3);

                referer = "http://www.ha.10086.cn/tiyan/SSOClient/ssoLogin.action?a=validateSSO&n=channel";
                string SSORespHtml = httpUtils.DoPost(SSOPOST_URL, sb.ToString(), referer, haRespCookieList, out respCookie);

                string SAMLart = "";
                AnalizeSSOData(SSORespHtml, out SAMLart, out RelayState);

                if (SAMLart == "" || RelayState == "")
                {
                    Log.PrintLog("第二层验证错误：" + SSORespHtml);
                }
                else
                {
                    sb = new StringBuilder("SAMLart=" + HttpUtility.UrlEncode(HttpUtility.HtmlDecode(SAMLart)));
                    sb.Append("&RelayState=" + HttpUtility.UrlEncode(HttpUtility.HtmlDecode(RelayState)));

                    string lastLoginHtml = httpUtils.DoPost(IMPLICITLOGIN_URL, sb.ToString(), referer, tiyanCookieList, out respCookie);
                    CookieCollection impCookieList = lib.parseSetCookie(respCookie, ".10086.cn");
                    for (int i = 0; i < impCookieList.Count; i++)
                    {
                        Cookie impTemp = impCookieList[i];
                        if (impTemp.Name == "TiyanWebtokenid")
                        {
                            TiyanWebtokenid = impTemp.Value;
                            tiyanCookieList.Add(impTemp);
                        }
                    }

                    string indexHtml = httpUtils.DoGet(VALIDATESSO_URL, "", tiyanCookieList, out respCookie);

                    suc = checkResult(indexHtml);
                    
                }
            }
            return suc;
        }

        public bool checkResult(string loginHtml)
        {
            bool suc = true;
            if (loginHtml.IndexOf("尊敬的") > 0)
            {
                suc = true;
            }
            else
            {
                suc = false;
            }
            return suc;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SSORespHtml"></param>
        /// <param name="SAMLart"></param>
        /// <param name="RelayState"></param>
        public static void AnalizeSSOData(string SSORespHtml, out string SAMLart, out string RelayState)
        {
            SAMLart = "";
            RelayState = "";

            try
            {
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(SSORespHtml);

                HtmlNode hidden1 = document.DocumentNode.SelectSingleNode("//input[@name=\"SAMLart\"]");
                HtmlNode hidden2 = document.DocumentNode.SelectSingleNode("//input[@name=\"RelayState\"]");

                if (hidden1 != null)
                {
                    SAMLart = hidden1.GetAttributeValue("value", "");
                }

                if (hidden2 != null)
                {
                    RelayState = hidden2.GetAttributeValue("value", "");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 解析html页面，获取 SAMLRequest 和 RelayState
        /// </summary>
        /// <param name="loginRespHtml"></param>
        /// <param name="SAMLRequest"></param>
        /// <param name="RelayState"></param>
        public static void AnalizeLoginData(string loginRespHtml, out string SAMLRequest, out string RelayState)
        {
            SAMLRequest = "";
            RelayState = "";
            try
            {

                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(loginRespHtml);

                HtmlNode hidden1 = document.DocumentNode.SelectSingleNode("//input[@name=\"SAMLRequest\"]");
                HtmlNode hidden2 = document.DocumentNode.SelectSingleNode("//input[@name=\"RelayState\"]");


                if (hidden1 != null)
                {
                    SAMLRequest = hidden1.GetAttributeValue("value", "");
                }

                if (hidden2 != null)
                {
                    RelayState = hidden2.GetAttributeValue("value", "");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string SSOPost(string SAMLRequest, string RelayState)
        {
            StringBuilder sb = new StringBuilder("SAMLRequest=" + SAMLRequest);
            sb.Append("&RelayState=" + RelayState);

            string respCookie = "";
            return httpUtils.DoPost(SSOPOST_URL, sb.ToString(), referer, out respCookie);
        }


        /// <summary>
        /// 获取指定月份的酬金情况
        /// </summary>
        /// <returns></returns>
        public string[] BRBD(string feeDate)
        {
            StringBuilder sb = new StringBuilder("month=" + feeDate);

            referer = "http://www.ha.10086.cn/tiyan/channel/tEReward.action";

            string respCookie = "";

            string html = httpUtils.DoPost(BRBD_URL, sb.ToString(), referer, tiyanCookieList, out respCookie);
            return AnalyzeBRBD(html);
        }

        /// <summary>
        /// 解析酬金数据转换为数组
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public string[] AnalyzeBRBD(string html)
        {
            string[] brbd = new string[2];
            html = html.Replace("</td>", ",").Replace("<td>", ",");
            string[] array = html.Split(',');
            if (array.Length >= 6)
            {
                string sucCount = array[3];
                string failCount = array[5];
                brbd[0] = sucCount;
                brbd[1] = failCount;
            }
            return brbd;

        }


        /// <summary>
        /// 获取指定月份的推荐情况, 日期格式为 yyyy-MM-月份最后一天
        /// </summary>
        /// <returns></returns>
        public string[] QEBDatas(string recDate)
        {
            StringBuilder sb = new StringBuilder("ymd=" + recDate);

            referer = "http://www.ha.10086.cn/tiyan/channel/tEBus.action";

            string respCookie = "";

            string html = httpUtils.DoPost(QEBDatas_URL, sb.ToString(), referer, tiyanCookieList, out respCookie);
            return AnalyzeBRBD(html);
        }

        /// <summary>
        /// 解析酬金数据转换为数组
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public string[] AnalyzeQEBDatas(string html)
        {
            string[] QEBDatas = new string[2];
            html = html.Replace("</td>", ",").Replace("<td>", ",");
            string[] array = html.Split(',');
            if (array.Length >= 6)
            {
                string sucCount = array[3];
                string failCount = array[5];
                QEBDatas[0] = sucCount;
                QEBDatas[1] = failCount;
            }
            return QEBDatas;

        }


        private string RECOMMAND_URL = "http://www.ha.10086.cn/tiyan/game/checkMsisdn.action";

        private string RECOMMAND_SENDINFO_URL = "http://www.ha.10086.cn/tiyan/game/sendInfoForClient.action";

        public string Post_Recommand(string phone)
        {
            string respCookie = "";
            referer = "http://www.ha.10086.cn/tiyan/channel/salearea.action";
            string param = "toMsisdn=" + phone;
            string result = httpUtils.DoPost(RECOMMAND_URL, param, referer, tiyanCookieList, out respCookie);
            return result;
        }

        public string Post_SendInfo(string phone, string busCode, string busName)
        {
            string respCookie = "";
            StringBuilder sb = new StringBuilder();
            sb.Append("busCode=" + busCode);
            sb.Append("&toMsisdn=" + phone);
            sb.Append("&busName=" + HttpUtility.UrlEncode(busName));
            string result = httpUtils.DoPost(RECOMMAND_SENDINFO_URL, sb.ToString(), referer, tiyanCookieList, out respCookie);
            return result;
        }
    }
}
